﻿





using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.SeqJits.Dtos;
using System.Linq.Dynamic.Core;
using KDS.Mes.Dto;
using KDS.Mes.Authorization;



namespace KDS.Mes.Mes.SeqJits
{
    /// <summary>
    /// 用于JIT生产的序列信息表服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Plan_SeqJits)]


    public class SeqJitAppService : MesAppServiceBase, ISeqJitAppService
    {
        private readonly IRepository<SeqJit, int> _seqJitRepository;
        private readonly ISeqJitListExcelExporter _seqJitListExcelExporter;


        private readonly SeqJitManage _seqJitManage;
        private readonly ISqlExecuter _sqlExecuter;

        /// <summary>
        /// 构造方法
        /// </summary>
        public SeqJitAppService(IRepository<SeqJit, int> seqJitRepository,SeqJitManage seqJitManage
      , ISeqJitListExcelExporter seqJitListExcelExporter, ISqlExecuter sqlExecuter)
        {
            _seqJitRepository = seqJitRepository;
            _seqJitManage = seqJitManage;
            _seqJitListExcelExporter = seqJitListExcelExporter;
            _sqlExecuter = sqlExecuter;
        }
        public void GetOrderChartData(SeqJitEditDto input)
        {
            string sql = "exec sp_Web_Create_Plan_Jit '" + input.WORK_DATE+ "','" + input.wh_area_id+ "','" + input.ALC_CD+ "','" + input.SEQ_NO+"'";
            var charts = _sqlExecuter.SqlQuery<SeqJitListDto>(sql).ToList();
            //return charts;
        }

        #region 实体的自定义扩展方法
        private IQueryable<SeqJit> _seqJitRepositoryAsNoTrack => _seqJitRepository.GetAll().AsNoTracking();


        #endregion


        #region 用于JIT生产的序列信息表管理

        /// <summary>
        /// 根据查询条件获取用于JIT生产的序列信息表分页列表
        /// </summary>
        public async Task<PagedResultDto<SeqJitListDto>> GetPagedSeqJitsAsync(GetSeqJitInput input)
        {

            var query = _seqJitRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件

            var seqJitCount = await query.CountAsync();

            var seqJits = await query
                
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var seqJitListDtos = seqJits.MapTo<List<SeqJitListDto>>();
            return new PagedResultDto<SeqJitListDto>(
            seqJitCount,
            seqJitListDtos
            );
        }

        public PagedResultDto<SeqJitListDto> GetPagedSeqJits(GetSeqJitInput input)
        {
            //初步过滤
            var query = _seqJitRepository.GetAll()
                .WhereIf(!input.wh_area_id.IsNullOrEmpty(), u => u.wh_area_id == input.wh_area_id)
                .WhereIf(!input.IF_FLAG.IsNullOrEmpty(), u => u.IF_FLAG == input.IF_FLAG)
                .WhereIf(!input.ALC_CD.IsNullOrEmpty(), u => u.ALC_CD == input.ALC_CD)
                .WhereIf(!input.Time1.ToString().IsNullOrEmpty(), u => u.CREATE_DTTM >= input.Time1)
                .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.CREATE_DTTM <= input.Time2);
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.WORK_DATE).ThenBy(x => x.SEQ_NO) : query.OrderBy(t => t.WORK_DATE).ThenBy(t => t.SEQ_NO);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<SeqJitListDto>(tasksCount, taskList.MapTo<List<SeqJitListDto>>());
        }

        /// <summary>
        /// 通过Id获取用于JIT生产的序列信息表信息进行编辑或修改 
        /// </summary>
        public async Task<GetSeqJitForEditOutput> GetSeqJitForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetSeqJitForEditOutput();

            SeqJitEditDto seqJitEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _seqJitRepository.GetAsync(input.Id.Value);
                seqJitEditDto = entity.MapTo<SeqJitEditDto>();
            }
            else
            {
                seqJitEditDto = new SeqJitEditDto();
            }

            output.SeqJit = seqJitEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取用于JIT生产的序列信息表ListDto信息
        /// </summary>
        public async Task<SeqJitListDto> GetSeqJitByIdAsync(EntityDto<int> input)
        {
            var entity = await _seqJitRepository.GetAsync(input.Id);

            return entity.MapTo<SeqJitListDto>();
        }







        /// <summary>
        /// 新增或更改用于JIT生产的序列信息表
        /// </summary>
        public async Task CreateOrUpdateSeqJitAsync(CreateOrUpdateSeqJitInput input)
        {
            if (input.SeqJitEditDto.Id.HasValue)
            {
                await UpdateSeqJitAsync(input.SeqJitEditDto);
            }
            else
            {
                await CreateSeqJitAsync(input.SeqJitEditDto);
            }
        }

        /// <summary>
        /// 新增用于JIT生产的序列信息表
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_SeqJits_Create)]
        public virtual async Task<SeqJitEditDto> CreateSeqJitAsync(SeqJitEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<SeqJit>();

            entity = await _seqJitRepository.InsertAsync(entity);
            return entity.MapTo<SeqJitEditDto>();
        }

        /// <summary>
        /// 编辑用于JIT生产的序列信息表
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_SeqJits_Edit)]
        public virtual async Task UpdateSeqJitAsync(SeqJitEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _seqJitRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _seqJitRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除用于JIT生产的序列信息表
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_SeqJits_Delete)]
        public async Task DeleteSeqJitAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _seqJitRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除用于JIT生产的序列信息表
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Plan_SeqJits_Delete)]
        public async Task BatchDeleteSeqJitAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _seqJitRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion
        #region 用于JIT生产的序列信息表的Excel导出功能


        public async Task<FileDto> GetSeqJitToExcel(SeqJitEditDto input)
        {
            string sql = "select top 20 * from T_N_BHMC_SEQ_III_JIT where wh_area_id='" + input.wh_area_id + "'and WORK_DATE >='" + input.WORK_DATE + "' and SEQ_NO >= '" + input.SEQ_NO + "'ORDER BY WORK_DATE,SEQ_NO ";
            var charts = _sqlExecuter.SqlQuery<SeqJit>(sql).ToList();

         
            //var entities = await _seqJitRepository.GetAll()
            //    .Where(u => u.wh_area_id == input.wh_area_id)

                
            //    .Where( u => Convert.ToDouble(u.SEQ_NO) >= Convert.ToDouble(input.SEQ_NO))
            //    .Where( u => u.WORK_DATE == input.WORK_DATE)
            //    .OrderBy(t => t.WORK_DATE).ThenBy(t => t.SEQ_NO)
            //    .Take(20)

            //    .ToListAsync();

            var dtos = charts.MapTo<List<SeqJitListDto>>();

            var fileDto = _seqJitListExcelExporter.ExportSeqJitToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
